﻿using LuShanTea.DTO;
using LuShanTea.Front.Web.App_Start;
using LuShanTea.Front.Web.Models;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Front.Web.Controllers
{
    public class OrderController : Controller
    {
        private UserDataHelper _userHelper = new UserDataHelper();

        public IUserService UserService { get; set; }

        public ICartService CartService { get; set; }

        public ICartRecordService CartRecordService { get; set; }

        public IOrderService OrderService { get; set; }

        public IOrderRecordService OrderRecordService { get; set; }

        public IAreaService AreaService { get; set; }

        public ICityService CityService { get; set; }

        public IIdNameService IdNameService { get; set; }

        public IProvinceService ProvinceService { get; set; }

        public IAddressService AddressService { get; set; }

        public IPackService PackService { get; set; }

        public IGoodService GoodService { get; set; }

        public IGoodImsSrcService GoodImsSrcService { get; set; }

        [IsLogin]
        // GET: Order
        public ActionResult Detailed(long orderId)
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Login");
            }

            var order = OrderService.GetById(orderId);

            if (order == null)
            {
                return RedirectToAction("UserOrder", "User");
            }

            if (order.StatusName != "未付款")
            {
                return RedirectToAction("UserOrder", "User");
            }

            //加载选项数据
            var payWays = GetPayWays();
            var receipts = GetReceipts().Reverse().ToArray();
            var express = GetExpress();
            var orderRecords = OrderRecordService.GetOrderRecordByOrderId(orderId);
            OrderInfoModel model = new OrderInfoModel()
            {
                Order = order,
                Express = express,
                PayWays = payWays,
                Receipts = receipts,
                OrderRecordModels = GetOrderRecordByOrder(order.Id),

                //todo:有待优化
                Addresses = AddressService.GetAddressByUserId(userid)
            };

            return View(model);
        }

        [IsLogin]
        public ActionResult SubmitOrder(OrderSubmitModel model)
        {
            //验证提交数据
            if (!ModelState.IsValid)
            {
                string errors = MVCHelper.GetValidMsg(ModelState);
                return Json(new AjaxResult { Status = "error", ErrorMsg = errors });
            }

            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "您还没有登录，即将跳转登录页面" });
            }

            //检查该订单是否属于该用户
            if (!OrderService.IsAnyOrderByUser(userid, model.OrderId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "not found orderId" });
            }

            //判断订单是否已经提交
            var order = OrderService.GetById(model.OrderId);
            if (order.StatusName != "未付款")
            {
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "该订单以过期" });
            }

            if (AddressService.GetAddressByUserCount(userid) <= 0)
            {
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "您还没有收货地址，请先添加收货地址!", Data = "/UserAddress/Index" });
            }

            //检查地址是否存在
            if (!AddressService.HasAddressByUser(userid, model.AddressId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "not found address" });
            }

            //检查其他选项
            if (!GetExpress().Any(e => e.Id == model.ExpressId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "not found express" });
            }
            if (!GetPayWays().Any(e => e.Id == model.PayWayId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "not found PayWayId" });
            }
            if (!GetReceipts().Any(e => e.Id == model.ReceiptId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "not found ReceiptId" });
            }

            OrderDTO dto = new OrderDTO();
            dto.Id = model.OrderId;
            dto.LeaveWord = model.LeaveWord;
            dto.PayWayId = model.PayWayId;
            dto.AddressId = model.AddressId;
            dto.Amount = order.Amount < 68 ? order.Amount + 15 : order.Amount;
            dto.StatusId = IdNameService.GetNameByTypeName("订单状态")
                .Where(s => s.Name == "已付款").First().Id;
            dto.ExpressId = model.ExpressId;
            dto.ReceiptId = model.ReceiptId;

            OrderService.UpdateOrder(dto);

            //TODO:优化
            CachRedis(userid);

            return Json(new AjaxResult { Status = "ok" });
        }

        private void CachRedis(long userid)
        {
            var userCollectModel = _userHelper.GetUserCollectModel(userid);
            var userOrderRecords = _userHelper.GetOrderRecords(userid, HttpContext, ViewData);

            
            using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("47.106.159.212:6379"))
            {
                IDatabase db = connection.GetDatabase();//默认是访问 db0 数据库，可以通过方法参数指定数字访问不同的数据库
                RedisHelper redis = new RedisHelper(db);
                redis.Add("LuShanTea_Order_UserCollectModel_userid_" + userid, userCollectModel);
                redis.Add("LuShanTea_Order_UserOrderRecords_userid_" + userid, userOrderRecords);
                redis.Add("LuShanTea_Order_OrderRecordCount_userid_" + userid, ViewData["OrderRecordCount"]);
            }
        }


        [IsLogin]
        [HttpPost]
        public ActionResult BuyNow(OrderByNowModel model)
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "您还没有登录，即将跳转登录页面" });
            }

            //判断商品是否存在
            var good = GoodService.GetByGoodId(model.GoodId);

            if (good == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "商品不存在!" });
            }

            //判断商品是否拥有该包装
            var packs = PackService.GetPackByGoodId(model.GoodId);
            bool flag = packs.Any(p => p.Id == model.PackId);
            if (!packs.Any(p => p.Id == model.PackId))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "该商品中不包含该包装!" });
            }

            //判断购买数量是否超出剩余数量
            long count = good.TotalCount - good.Selled;
            if (count < model.Count)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "购买数量超出剩余数量" });
            }

            if (AddressService.GetAddressByUserCount(userid) <= 0)
            {
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "您还没有收货地址，即将跳转页面!", Data = "/UserAddress/Index" });
            }

            //构造信息和cart无关，只是借用他方便传值
            CartRecordDTO dto = new CartRecordDTO();
            dto.Count = model.Count;
            dto.GoodId = model.GoodId;
            dto.GoodPrice = good.Price;
            dto.PackId = model.PackId;
            long orderid = CreateOrder(userid, dto);

            return Json(new AjaxResult { Status = "ok", Data = orderid });
        }

        [IsLogin]
        public ActionResult CreateByCart()
        {
            long userid = UserHelper.GetUserId(HttpContext);

            //获取用户数据
            var user = UserService.GetById(userid);

            //判断用户是否存在
            if (user == null)
            {
                return RedirectToAction("Index", "Login");
            }

            if (AddressService.GetAddressByUserCount(userid) <= 0)
            {
                //return RedirectToAction("UserAddress", "Index");
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "您还没有收货地址，请先添加收货地址!", Data = "/UserAddress/Index" });
            }

            #region 获取用户购物车信息
            long cartId = CartService.GetCartIdByUserId(userid);

            var cartRecordDTOs = CartRecordService.GetBuyCartByCartId(cartId);

            if (cartRecordDTOs.Count() <= 0)
            {
                return Redirect("~/Cart/Index");
            }

            var orderId = CreateOrder(userid, cartRecordDTOs);

            //将购买的商品从购物车中清除
            foreach (var cartRe in cartRecordDTOs)
            {
                //CartRecordService.BuyGood(cartRe.Id);
                CartRecordService.MarkDelete(cartRe.Id);
            }

            #endregion

            return RedirectToAction("Detailed", new { OrderId = orderId });
        }

        /// <summary>
        /// 初始化订单数据
        /// </summary>
        /// <returns></returns>
        private long CreateOrder(long userId, params CartRecordDTO[] cartRecordDTOs)
        {
            //总价格
            float amount = 0;
            foreach (var cartRecord in cartRecordDTOs)
            {
                var pack = PackService.GetById(cartRecord.PackId);
                amount += cartRecord.Count * (cartRecord.GoodPrice + pack.Price);

            }

            //amount = amount < 68 ? amount + 15 : amount;

            long? addressId = AddressService.GetFirstAddressIdByUserId(userId);

            OrderAddNewDTO orderAddNewDTO = new OrderAddNewDTO();

            //初始化数据
            orderAddNewDTO.AddressId = addressId;
            orderAddNewDTO.Amount = amount;
            orderAddNewDTO.ExpressId = 11;
            orderAddNewDTO.Guid = Guid.NewGuid().ToString();
            orderAddNewDTO.PaywayId = 2;
            orderAddNewDTO.ReceiptId = 16;
            orderAddNewDTO.UserId = userId;

            long orderId = OrderService.AddNew(orderAddNewDTO);

            AddOrderRecord(orderId, cartRecordDTOs);

            return orderId;
        }

        /// <summary>
        /// 添加订单记录
        /// </summary>
        private void AddOrderRecord(long orderId, params CartRecordDTO[] cartRecordDTOs)
        {
            foreach (var cartRecord in cartRecordDTOs)
            {
                var pack = PackService.GetById(cartRecord.PackId);
                OrderRecordAddNewDTO orderRecordAddNewDTO = new OrderRecordAddNewDTO();
                orderRecordAddNewDTO.OrderId = orderId;
                orderRecordAddNewDTO.PackId = cartRecord.PackId;
                orderRecordAddNewDTO.Price = (cartRecord.GoodPrice + pack.Price) * cartRecord.Count;
                orderRecordAddNewDTO.Count = cartRecord.Count;
                orderRecordAddNewDTO.GoodId = cartRecord.GoodId;


                OrderRecordService.AddNew(orderRecordAddNewDTO);

                //更新销售量
                GoodService.UpdataGoodSelled(cartRecord.GoodId, cartRecord.Count);
            }

        }

        private IdNameDTO[] GetExpress()
        {
            var express = IdNameService.GetNameByTypeName("快递公司");
            return express;
        }

        private IdNameDTO[] GetPayWays()
        {
            var payWays = IdNameService.GetNameByTypeName("付款方式");
            return payWays;
        }

        private IdNameDTO[] GetReceipts()
        {
            var receipts = IdNameService.GetNameByTypeName("发票类型");
            return receipts;
        }

        private OrderRecordModel[] GetOrderRecordByOrder(long orderId)
        {
            List<OrderRecordModel> listModel = new List<OrderRecordModel>();

            //获取订单下的订单记录来
            OrderRecordDTO[] orderRecordDTOs = OrderRecordService.GetOrderRecordByOrderId(orderId);

            foreach (var orderRe in orderRecordDTOs)
            {
                //获取订单记录里的商品图片
                GoodImgSrcDTO goodImgSrcDTO = GoodImsSrcService.GetFirstImgByGoodId(orderRe.GoodId);

                string imgSrc = goodImgSrcDTO == null ? "" : goodImgSrcDTO.ImgSrc;

                listModel.Add(new OrderRecordModel { OrderRecord = orderRe, ImgSrc = imgSrc });
            }




            return listModel.ToArray();
        }
    }
}